﻿using System.Collections.ObjectModel;

namespace MefContrib.Models.Provider.Definitions.Configurable
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Diagnostics;
    using System.Linq;

    /// <summary>
    /// 
    /// </summary>
    public class PartCatalogConfigurationImportCollection : ConfigurationElementCollection
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PartCatalogConfigurationImportCollection"/>
        /// </summary>
        public PartCatalogConfigurationImportCollection()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public Collection<ImportDescription> AsCollection()
        {
            Collection<ImportDescription> imports
                = new Collection<ImportDescription>();

            foreach (PartCatalogConfigurationImport import in this)
            {
                imports.Add(
                    new ImportDescription
                    {
                        AllowDefault = import.AllowDefault,
                        Contract = import.Contract,
                        MemberName = import.Member,
                        Prerequisite = import.IsPrerequisite,
                        Recomposable = import.IsRecomposable,
                        RequiredMetadata = new Collection<string>(import.Metadata.AsDictionary().Keys.ToList()),
                    }
                );
            }

            return imports;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override ConfigurationElement CreateNewElement()
        {
            return new PartCatalogConfigurationImport();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ConfigurationElementCollectionType CollectionType
        {
            [DebuggerStepThrough]
            get { return ConfigurationElementCollectionType.BasicMap; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override string ElementName
        {
            [DebuggerStepThrough]
            get { return "import"; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            PartCatalogConfigurationImport part =
                element as PartCatalogConfigurationImport;

            if (part != null)
            {
                return part.Member;
            }

            throw new InvalidOperationException();
        }
    }
}